package com.baidu.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baidu.shop.base.BaseApiService;
import com.baidu.shop.base.Result;
import com.baidu.shop.config.JwtConfig;
import com.baidu.shop.dto.Car;
import com.baidu.shop.dto.SkuDTO;
import com.baidu.shop.dto.SpecParamDTO;
import com.baidu.shop.dto.UserInfo;
import com.baidu.shop.entity.SkuEntity;
import com.baidu.shop.entity.SpecParamEntity;
import com.baidu.shop.feign.GoodsFeign;
import com.baidu.shop.redis.repository.RedisRepository;
import com.baidu.shop.service.CarService;
import com.baidu.shop.utils.JSONUtil;
import com.baidu.shop.utils.JwtUtils;
import com.baidu.shop.utils.ObjectUtil;
import com.baidu.shop.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description:
 * @ClassName: CarServiceImpl
 * @Author: User
 * @date: 2020.10.19 19:10
 * @version: 1.0
 */
@RestController
@Slf4j
public class CarServiceImpl  extends BaseApiService implements CarService {
    @Autowired
    private RedisRepository redisRepository;
    @Resource
    private JwtConfig jwtConfig;
    @Resource
    private GoodsFeign goodsFeign;

    public static String GOODS_CAR_PRE = "goods_car_";

    public static String GOODS_DEl_CAR_PRE = "goods_del_car_";

    @Override
    public Result<JSONObject> recoverCar(String recoverId, String token) {
        try {
            UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
            String recover = JSONObject.parseObject(recoverId).getObject("recoverId", String.class);
               //获取要恢复的商品 ,从删除购物车
                Car recoverCar = redisRepository.getHash(GOODS_DEl_CAR_PRE + infoFromToken.getId(), recover, Car.class);
               if (ObjectUtil.isNotNull(recoverCar)){
                   //将恢复的商品添加到购物车redis中
                   redisRepository.setHash(GOODS_CAR_PRE+infoFromToken.getId(),recover,JSONUtil.toJsonString(recoverCar));
                   //删除redis删除购物车中这个要恢复商品
                   redisRepository.delHash(GOODS_DEl_CAR_PRE + infoFromToken.getId(),recover);
               }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.setResultSuccess();
    }

    @Override
    public Result<JSONObject> delCar(String delCarIds, String token) {
        try {
            UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
            Arrays.asList(delCarIds.split(",")).forEach(delId->{
                 //获取要删除的商品
                 Car delCar = redisRepository.getHash(GOODS_CAR_PRE + infoFromToken.getId(), delId, Car.class);
                if (ObjectUtil.isNotNull(delCar)) {
                    //将删除的商品添加到删除购物车redis中
                    redisRepository.setHash(GOODS_DEl_CAR_PRE + infoFromToken.getId(), delId, JSONUtil.toJsonString(delCar));
                    //删除redis购物车中这个商品
                    redisRepository.delHash(GOODS_CAR_PRE + infoFromToken.getId(), delId);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.setResultSuccess();
    }

    @Override
    public Result<JSONObject> carNumUpdate(Long skuId, Integer type, String token) {

        try {
            UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
            Car hash = redisRepository.getHash(GOODS_CAR_PRE + infoFromToken.getId(), skuId.toString(), Car.class);
            if (ObjectUtil.isNotNull(hash)) {
                if (type==1){
                    hash.setNum(hash.getNum()+1);
                }else{
                    hash.setNum(hash.getNum()-1);
                }
                boolean b = redisRepository.setHash(GOODS_CAR_PRE + infoFromToken.getId(), skuId.toString(), JSONUtil.toJsonString(hash));
                log.debug("修改reids 商品{} 数量成功{}",skuId,hash.getNum());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return this.setResultSuccess();
    }

    @Override
    public Result<HashMap<String, List<Car>>> getUserGoodsCar(String token) {
        HashMap<String, List<Car>> carListHashMap = new HashMap<>();
        List<Car> carList =new ArrayList<>();
        List<Car> delCarList =new ArrayList<>();
        try {
            UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
            Map<String, String> hash = redisRepository.getHash(GOODS_CAR_PRE + infoFromToken.getId());
            hash.forEach((key,value)->{
               carList.add(JSONUtil.toBean(value, Car.class));
            });

            Map<String, String> delhash = redisRepository.getHash(GOODS_DEl_CAR_PRE + infoFromToken.getId());
            delhash.forEach((key,value)->{
                delCarList.add(JSONUtil.toBean(value, Car.class));
            });
            carListHashMap.put("carList",carList);
            carListHashMap.put("delCarList",delCarList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.setResultSuccess(carListHashMap);
    }

    @Override
    public Result<JSONObject> mergeCar(String clientCarList, String token) {
        JSONObject jsonObject = JSONObject.parseObject(clientCarList);
        List<Car> carList = JSONObject.parseArray(jsonObject.getJSONArray("clientCarList").toJSONString(), Car.class);
        carList.stream().forEach(car -> addCar(car, token));
        return this.setResultSuccess();
    }

    @Override
    public Result<JSONObject> addCar(Car car,String token) {
        try {
            UserInfo infoFromToken = JwtUtils.getInfoFromToken(token, jwtConfig.getPublicKey());
            log.debug("从redis中获取数据{}",infoFromToken);
            Car userCarItem = redisRepository.getHash(GOODS_CAR_PRE + infoFromToken.getId(), car.getSkuId() + "", Car.class);

            if (userCarItem ==null){
            log.debug("当前用户 {} 没有将sku：{} 添加到购物车",infoFromToken.getUsername(),car.getSkuId());
                Result<SkuEntity> skuBySkuId = goodsFeign.getSkuBySkuId(car.getSkuId());
                if (skuBySkuId.getCode()==200){
                    SkuEntity data = skuBySkuId.getData();
                    car.setImage(StringUtil.isEmpty(data.getImages()) ? "":data.getImages().split(",")[0]);
                    car.setPrice(data.getPrice().longValue());
                    car.setTitle(data.getTitle());
                    car.setUserId(infoFromToken.getId());

                    SpecParamDTO specParamDTO = new SpecParamDTO();
                    specParamDTO.setGeneric(false);
                    Map<String,Object> ownSpec = new HashMap();
                    Map<String,String> specGen = new HashMap();
                    Result<List<SpecParamEntity>> specParamInfo = goodsFeign.getSpecParamInfo(specParamDTO);
                    if (specParamInfo.getCode()==200){
                         specParamInfo.getData().stream().forEach(spec->{
                             specGen.put(spec.getId().toString(), spec.getName());
                         });
                        Map<String, Object> own = JSONUtil.toMap(data.getOwnSpec());
                        own.forEach((key,value)->{
                             ownSpec.put(specGen.get(key),value);
                        });
                    }
                    car.setOwnSpec(JSONUtil.toJsonString(ownSpec));
                }
                boolean b = redisRepository.setHash(GOODS_CAR_PRE + infoFromToken.getId(), car.getSkuId() + "", JSONUtil.toJsonString(car));
                log.debug("添加redis结果:{},hashkey:{},mapkey:{}", b,GOODS_CAR_PRE +infoFromToken.getId(),car.getSkuId());
            }else{
                log.debug("当前用户 {} 以前添加过sku : {} 的数据,更改购物车对应的商品数量为 : {}",infoFromToken.getUsername(),car.getSkuId(),userCarItem.getNum() + car.getNum());
                userCarItem.setNum(userCarItem.getNum()+car.getNum());
                boolean b = redisRepository.setHash(GOODS_CAR_PRE + infoFromToken.getId(), car.getSkuId() + "", JSONUtil.toJsonString(userCarItem));
                log.debug("添加redis结果:{},hashkey:{},mapkey:{}", b,GOODS_CAR_PRE +infoFromToken.getId(),car.getSkuId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("=========");
        return this.setResultSuccess();
    }
}
